package oa.hleast.xswl.utils;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ClassUtils {

    public static String getPostParams(Object clazz) {
        Field[] fields = clazz.getClass().getDeclaredFields();
        System.out.println("fields =" + fields);

        StringBuilder requestURL = new StringBuilder();
        try {
            boolean flag = true;
            String property, value;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                // 允许访问私有变量
                field.setAccessible(true);

                // 属性名
                property = field.getName();
                // 属性值
                if (ObjectUtils.isNotEmpty(field.get(clazz))) {
                    value = field.get(clazz).toString();
                    requestURL.append(property).append("=").append(value).append("&");
                } else {
                    log.info("属性 property = {},值为null", property);
                }
            }

            requestURL = requestURL.delete(requestURL.length() - 1, requestURL.length());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return requestURL.toString();
    }

    public static  Map<String,Object> class2Map(Object clazz) {
        Field[] fields = clazz.getClass().getDeclaredFields();
        System.out.println("fields =" + fields);

        Map<String,Object> map = new HashMap<>();
        try {
            String property, value;
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                // 允许访问私有变量
                field.setAccessible(true);

                // 属性名
                property = field.getName();
                // 属性值
                if (ObjectUtils.isNotEmpty(field.get(clazz))) {
                    value = field.get(clazz).toString();
                    map.put(property,value);
                } else {
                    log.info("属性 property = {},值为null", property);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) {

    }
}
